import { zalert, toast } from '@/utils/utils'
import { API_BASE_URL } from '@/utils/apiUrl'
type RequestOptionsMethod = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'

interface baseConfig {
  url: string
  method: RequestOptionsMethod
  header?: any
  data?: Record<string, any>
  params?: Record<string, any>
  showLoading?: boolean
}

export interface CustomSuccessData<T = any> {
  code: number
  msg?: string
  message?: string
  data?: T
  [keys: string]: any
}

// 
function ajaxFilter(data: any) {
  let status = true
  if (data.code == 401) {
    status = false
    // cosn
    zalert('Login status invalid', () => {
      uni.removeStorageSync('token')
      uni.reLaunch({
        url: '/pages/login/index',
      })
    })
  }
  return status
}
function getCurrentDomain() {
  const host = window.location.host
  if (host.indexOf('localhost') !== -1 || host.indexOf('127.0.0.1') !== -1 || host.indexOf('192.168.0.71') !== -1) {
    // return 'kongs.vip' // 
	 return 'qoojee.vip' // 
  }
  return host
}
/**
 * 
 */
const baseRequest = <T>(config: baseConfig) => {
  // if (!config.showLoading) {
  // 	uni.showLoading({
  // 		title: 'Loading...',
  // 		mask: true,
  // 	})
  // }
  if (config.method === 'GET' && config.params) {
    let url = config.url + '?'
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName]
      const part = encodeURIComponent(propName) + '='
      if (value !== null && typeof value !== 'undefined') {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            url += subPart + encodeURIComponent(value[key]) + '&'
          }
        } else {
          url += part + encodeURIComponent(value) + '&'
        }
      }
    }
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  const Url = API_BASE_URL()
  // const Url = import.meta.env.VITE_API_URL as string
  // console.log(Url)
  // const token = uni.getStorageSync('token')
    if (config.header) {
      config.header['x-token'] = uni.getStorageSync('token')
      config.header['h5-platform'] = getCurrentDomain()
    } else {
      config.header = {
        'x-token': uni.getStorageSync('token'),
        'h5-platform': getCurrentDomain(),
      }
    }
  return new Promise<CustomSuccessData<T>>((reslove, reject) => {
    // uni.showLoading({
    // 	title: 'Loading',
    // 	mask: true,
    // })
    uni.request({
      url: Url + config.url,
      method: config.method || 'GET',
      header: config.header,
      data: config.data || {},
      success: (res: any) => {
        if (res.data.code == 77) {
          uni.hideLoading()
          const hasVisited = uni.getStorageSync('hasVisited')
          if (hasVisited) {
            uni.navigateTo({
              url: '/pages/login/index',
            })
          }
          // uni.showModal({
          // 	// title: `${t('Not Logged In')}`,
          // 	// content: `${t('Please log in first')}！`,
          // 	title: `${'Not Logged In'}`,
          // 	content: `${'Please log in first'}！`,
          // 	confirmText: 'Login',  // 
          // 	cancelText: 'Cancel',     // 
          // 	confirmColor: '#FE8400',
          // 	success: (res) => {
          // 		if (res.confirm) {
          // 			// ，
          // 			uni.navigateTo({
          // 				url: '/pages/login/index'
          // 			});
          // 		} else {
          // 			uni.reLaunch({
          // 				url: '/pages/index/index'
          // 			});
          // 		}
          // 	}
          // });
        }
        if (!config.showLoading) {
          uni.hideLoading()
        }
        if (ajaxFilter(res.data) && res.statusCode == 200) {
          reslove(res.data)
        } else if (res.data.code != 401) {
          toast(res.data.msg)
          reject(res)
        }
      },
      fail: (res: any) => {
        if (!config.showLoading) {
          uni.hideLoading()
        }
        if (res.msg && res.msg.indexOf('timeout') !== -1) {
          zalert('Request timed out, please try again later')
        } else if (res.msg && res.msg.indexOf('request') !== -1) {
          zalert('The server has been shut down')
        } else {
          zalert('Request failed, please check the network')
        }
        reject('request failure')
      },
    })
  })
}

export default baseRequest
